package com.sopaths.crawler.$51job;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;

import javax.inject.Named;

import org.apache.http.client.utils.URIBuilder;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.sopaths.contract.crawler.RecruitmentSummary;
import com.sopaths.crawler.SummaryCrawler;
import com.sopaths.crawler.tasks.SummaryCrawlerTask;

@Named("51JobSummaryCrawler")
public class $51JobSummaryCrawler extends SummaryCrawler {

	private Logger logger = Logger.getLogger($51JobSummaryCrawler.class);

	@Override
	public String assembleSummaryUrl(SummaryCrawlerTask task) {
		try {
			URI uri = new URIBuilder().setScheme("http")
					.setHost("search.51job.com")
					.setPath("/jobsearch/search_result.php")
					.addParameter("jobarea", task.getCity().getCode())
					.addParameter("district", "000000")
					.addParameter("funtype", "0000")
					.addParameter("industrytype", "00")
					.addParameter("issuedate", "9")
					.addParameter("providesalary", "99")
					.addParameter("keywordtype", "2")
					.addParameter("curr_page", String.valueOf(task.getPage()))
					.addParameter("lang", "c")
					.addParameter("stype", "2")
					.addParameter("postchannel", "0000")
					.addParameter("workyear", "99")
					.addParameter("cotype", "99")
					.addParameter("degreefrom", "99")
					.addParameter("jobterm", "01")
					.addParameter("lonlat", "0%2C0")
					.addParameter("radius", "-1")
					.addParameter("ord_field", "0")
					.addParameter("list_type", "0")
					.addParameter("fromType", "14")
					.build();
			return uri.toString();
		} catch (URISyntaxException ex) {
			logger.error("An error occurred while assembling url.", ex);
			throw new RuntimeException(ex);
		}

	}

	@Override
	public void assembleSummaryTaskResult(SummaryCrawlerTask task, Document document) {
		List<RecruitmentSummary> recruitmentSummaries = new LinkedList<>();
		Elements summaryElements = document.select("#resultList tbody tr.tr0");
		for (Element summaryElement : summaryElements) {
			String url = summaryElement.select(".td1 a").attr("href");
			RecruitmentSummary recruitmentSummary = new RecruitmentSummary();
			recruitmentSummary.setUrl(url);
			recruitmentSummaries.add(recruitmentSummary);
		}
		task.setResult(recruitmentSummaries);
	}
}
